<?php

namespace Admin\Controller;

use Exception;
use Core\Session\AdminSessionHelper;
use Logger;
use Core\Controller\BaseController;
use Model\UserTable;
use Zend\Config\Processor\Constant;
use Zend\Mvc\MvcEvent;


class LoginController extends BaseController {



    public function onDispatch(MvcEvent $e)
    {
        $this->layout('login_layout');
        return parent::onDispatch($e); //
    }


    public function indexAction() {

    }

    public function loginAction()
    {
        try {
            $password = $this->params()->fromPost('txtPassword');
            $userName = $this->params()->fromPost('txtName');
            $userTable = $this->getTableFinder()->getUserTable();
            $userItem = $userTable->getUserByName($userName);
            if($userItem){
                $digestService = $this->getDigestService();
                if($userItem->password == $digestService->getUserPassword($userName, $password)){
                    AdminSessionHelper::setUser($userItem);
                    $date = new \DateTime();
                    AdminSessionHelper::setLoginTime($date);
                    $this->redirect()->toRoute("admin/index",array());
                }
                else{
                    throw new \Core\Exception\BusinessException('Thông tin đăng nhập không hợp lệ');
                }
            }else{
                throw new \Core\Exception\BusinessException('Thông tin đăng nhập không hợp lệ');
            }

        }
        catch (Exception $e) {
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            $this->redirect()->toRoute('admin/login', array());
        }


    }

}